package com.example.rubbish.Ui;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.rubbish.R;


public class ClearEditText extends androidx.appcompat.widget.AppCompatEditText {
    //一键清空图标
    private Drawable clearDrawable;
    //左侧搜索图标
    private Drawable searchDrawable;

    /**
     * void init()
     * 初始化图标资源
     */

    public ClearEditText(@NonNull Context context) {
        super(context);
        init();
    }

    public ClearEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ClearEditText(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        clearDrawable = getResources().getDrawable(R.drawable.edit_delete);
        searchDrawable = getResources().getDrawable(R.drawable.searchicon);
        //设置左侧搜索图标
        setCompoundDrawablesWithIntrinsicBounds(searchDrawable,
                null, null, null);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        setClearDrawableVisible(hasFocus() && text.length() > 0);

    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        setClearDrawableVisible(focused && length() > 0);
    }

    //显示删除图标
    private void setClearDrawableVisible(boolean visible) {
        setCompoundDrawablesWithIntrinsicBounds(searchDrawable, null,
                visible ? clearDrawable : null, null);
    }

    //点击删除图标->删除
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_UP) {
            Drawable drawable = clearDrawable;
            float x1 = getWidth() - getPaddingRight() - drawable.getBounds().width();
            float x2 = getWidth() - getPaddingRight();
            if (drawable != null && event.getX() >= x1 && event.getX() <= x2) {
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }
}
